<?php
/**
 * Created by PhpStorm.
 * User: 牛赞赞
 * Date: 2021/4/21
 * Time: 16:54
 */

namespace App\Model;


use Hyperf\DbConnection\Db;

class MemberCoupon extends Model
{
    protected $table = 'member_coupon';
    protected $fillable = ['cpns_code', 'cpns_id', 'uid', 'status', 'expire_time', 'create_time', 'cpns_hash', 'cpns_source'];
    public $timestamps = false;

    // 分配优惠券
    public static function assignCoupons($where, $data)
    {
        try {
            $coupon = Db::table('coupons')->where($where)->first();
            if (!$coupon) {
                return ['code' => 2, 'msg' => '优惠券已失效或不存在'];
            }
        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
        $member['uid'] = $data['uid'];
        $member['expire_time'] = time() + ($data['cpns_expire'] * 24 * 60 * 60);
        $member['create_time'] = time();
        $member['cpns_id'] = $data['cpns_id'];
        $member['cpns_hash'] = $data['cpns_hash'];
        $cpns_code = self::get_cpns_code($data['cpns_prefix'], $data['cpns_key']);
        $member['cpns_code'] = $cpns_code;
        try {
            Db::table('member_coupon')->insert($member);
            return ['code' => 0, 'msg' => 'OK', 'data' => ['cpns_code' => $cpns_code]];
        } catch (\Exception $e) {
            return ['code' => 3, 'msg' => $e->getMessage()];
        }
    }

    // 生成优惠券券码
    public static function get_cpns_code($cpns_prefix, $cpns_key)
    {
        $rand_key = rand_str(6);
        $coupon_serice = md5($cpns_prefix . $cpns_key . $rand_key);
        return $cpns_prefix . $rand_key . mj_sub_str($coupon_serice, 0, 6);
    }
}